#include "definicoes.h"

void insereI(char * filename);
void add_indiceI(int id, long seek);
void add_ind_sec_ind(int esp, int ind, long seek);


void insereI(char * filename){  /*insere o registro no fim do arquivo*/
  FILE *fw, *fr;
  individuo ind;
  int i;
  long seek;

  if(!(fw = fopen("individuos.txt", "w+"))){
    printf ("Arquivo nao encontrado!\n"); 
    return;
  }
  if ((fr = fopen( filename , "r" )) == NULL){
    printf("Erro ao abrir o arquivo!");
    return;
  }
  fscanf(fr, "%d\n", &num_ind);
  for(i=0; i < num_ind; i++){//controla numero de registros a ser inserido
    seek = ftell(fw);
    fscanf(fr, "%d|%d|%c\n", &(ind.idEspecie), &(ind.idIndividuo), &(ind.sexo));
    fprintf(fw,"%d # %d # %c\n",ind.idEspecie, ind.idIndividuo, ind.sexo);
    add_indiceI(ind.idIndividuo, seek);
    add_ind_sec_ind(ind.idEspecie, ind.idIndividuo, seek);
  }
  fclose(fw);
  fclose(fr);
  return;
}

void add_indiceI(int id, long seek){
  indice * aux, * link;
  for(aux = indice_indiv; (aux->prox != NULL && aux->prox->indice < id); aux = aux->prox); /*Percorre o indice ate que o novo no seja colocado apos o no atual*/
  link = aux->prox;
  aux->prox = (indice *) malloc (sizeof(indice));
  aux = aux->prox;
  aux->indice = id;
  aux->offset = seek;
  aux->prox = link;
}
		  
void add_ind_sec_ind(int esp, int ind, long seek){
  ind_sec * ind_aux, * link_ind;
  list * list_aux, * link_list;
  ind_aux = busca_esp(esp);
  if(ind_aux){
    for(list_aux = ind_aux->lista;
	(list_aux->prox != NULL && list_aux->prox->id < ind);
	list_aux = list_aux->prox);
    link_list= list_aux->prox;
    list_aux->prox = (list *) malloc (sizeof(list));
    list_aux = list_aux->prox;
    list_aux->id = ind;
    list_aux->offset = seek;
    list_aux->prox = link_list;
  }
  else{
    for(ind_aux = ind_sec_ind;
	(ind_aux->prox != NULL && ind_aux->prox->indice < esp);
	ind_aux = ind_aux->prox);
    link_ind = ind_aux->prox;
    ind_aux->prox = (ind_sec *) malloc (sizeof(ind_sec));
    ind_aux = ind_aux->prox;
    ind_aux->indice = esp;
    ind_aux->lista = (list *) malloc (sizeof(list));
    list_aux = ind_aux->lista;
    list_aux->id = ind;
    list_aux->offset = seek;
    list_aux->prox = NULL;
    ind_aux->prox = link_ind;
  }
}

